﻿namespace BEGDC.CC.Web.UserControls.ESC
{
	using System;
	using System.Data;
	using System.Drawing;
	using System.Web;
	using System.Collections;
	using System.Web.UI.WebControls;
	using System.Web.UI.HtmlControls;
	using BEGDC.CC.BL.CCFlow.ESC;
	using BEGDC.CC.BL.CCFlow.CV;
	using BEGDC.CC.Entity;
	using BEGDC.CC.BL.Common.Query;
	using BEGDC.CC.BL.Workflow;
	using BEGDC.CC.BL.Common;
	using BEGDC.Utility.Castle;
	using BEGDC.CC.BL.UserManagement;
	using BEGDC.Utility.ExceptionManagement;

	/// <summary>
	///		Summary description for NormalRequest.
	/// </summary>
	public class ESCReadOnlyForm : BaseESC
	{
		#region Variables
		protected BEGDC.CC.Web.UserControls.ESC.ESCCtrl ESCCtrl;
		protected BEGDC.CC.Web.UserControls.Export ctrlExport;
		protected System.Web.UI.WebControls.TextBox tbOperationFlag1;
		protected System.Web.UI.WebControls.Label tx_AppState;
		protected System.Web.UI.WebControls.Label lbAppNo;
		protected System.Web.UI.HtmlControls.HtmlInputHidden hiddenScrollHight;
		protected System.Web.UI.WebControls.TextBox Ctl_hiddenDept;
		protected System.Web.UI.WebControls.TextBox Ctl_hiddenBranch;
		protected System.Web.UI.WebControls.TextBox tbComment;
		protected System.Web.UI.WebControls.TextBox tbOperationFlag;
//		protected System.Web.UI.HtmlControls.HtmlGenericControl SampleEZ;
//		protected System.Web.UI.HtmlControls.HtmlGenericControl SampleNormal;
		protected bool _Transition = false;
		public bool isReadOnly = false;
		bool saveBeforeSubmit=false;//joan 2008/8/23
		#endregion

		#region Properties
		private bool IsQuery
		{
			get
			{
				string state = this.Request.QueryString["State"];
				if(state == null) return false;
				return state == SysDicItem.ProjectStatusFlag.QUERY;
			}
		}

		private bool IsView
		{
			get
			{
				string state = this.Request.QueryString["State"];
				if(state == null) return false;
				if(state == SysDicItem.ProjectStatusFlag.View || state == SysDicItem.ProjectStatusFlag.CANCEL
					|| state == SysDicItem.ProjectStatusFlag.Pending || state == SysDicItem.ProjectStatusFlag.End
					|| state == SysDicItem.ProjectStatusFlag.Participation)
					return true;
				else
					return false;
			}
		}
		protected string Step
		{
			get
			{
				IQuery queryService = BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.QueryService] as IQuery;
				FlowInstance flowInstance = queryService.QueryFlowInstance( this.AppID );
				if( flowInstance == null )
					return WorkTransition.Draft;
				else
					return flowInstance.CurrentActiveStep.StepCode;
			}
		}
		#endregion

		private void Page_Load(object sender, System.EventArgs e)
		{
			if(!this.IsPostBack)
			{
				#region Invalid Session
				Session[SessionFlag.AccompanySession] = null;
				Session[SessionFlag.CustomerSession] = null;
				Session[SessionFlag.AccompanySessionEZ] = null;
				Session[SessionFlag.CustomerSessionEZ] = null;

				Session[SessionFlag.CompanyCarSession] = null;
				Session[SessionFlag.CompanyCarSessionEZ] = null;
				Session[SessionFlag.LeaseCarSession] = null;
				Session[SessionFlag.LeaseCarSessionEZ] = null;
				Session[SessionFlag.HotelSession] = null;
				Session[SessionFlag.HotelSessionEZ] = null;

				Session[SessionFlag.ContractInfo] = null;
				Session[SessionFlag.CostCenter] = null;
				#endregion

				base.PreInitForm();
				BuildFormProperties();

				ButtonStatusSetting();
				InitForm();
			}
		}

		#region ControlStatusSetting
		private void ControlStatusSetting(Accessibility access )
		{
			if( access == Accessibility.Readonly )
			{
				this.DisableChildrenControls(this);
				//this.stampCtrl1.Visible = false;
			}
		}
		#endregion

		#region Form Properties
		protected bool Transition
		{
			get
			{ 
				string TranStr = (string)this.ViewState["Transition"];
				if(TranStr=="1")
				{
					return true;
				}
				else
				{
					return false;
				}
			}
			set
			{ 
				if(value)
				{
					this.ViewState["Transition"] = "1";
				}
				else
				{
					this.ViewState["Transition"] = "0";
				}
			}
		}
		#endregion

		#region Build Form Properties
		private void BuildFormProperties()
		{
			IUser userService = AppContainer.Instance[ServiceConst.UserService] as IUser;
			Employee CurrentRequestor = userService.GetUser(HttpContext.Current.User.Identity.Name);

			if(CurrentRequestor.Department!=null)
			{
				//				this.Branch = CurrentRequestor.Department.Id.ToString();
				//				this.Ctl_hiddenBranch.Text = this.Branch;
				//				this.Department = CurrentRequestor.Department.DepartmentType.DicItemKey;
				//				this.Ctl_hiddenDept.Text = this.Department;
			}

			string TranStr = Request.QueryString["Transition"];

			if(TranStr!=null&&TranStr!="")
			{
				if(TranStr=="1")
				{
					this.Transition = true;
				}
				else
				{
					this.Transition = false;
				}
			}
		}
		#endregion

		#region InitForm
		private void InitForm()
		{
			long flowId  = this.LoadApplication();

			if(this.Application!=null)
			{
				if(this.Application.AppNo != string.Empty)
                    this.lbAppNo.Text = " Application No: " + this.Application.AppNo ;
				this.Transition = this.Application.IsTransition;


				//SET PROPERTIES OF FORM CONTROL AND LOAD CTRL
				ESCCtrl.isCoveredPerson = !this.Transition;
				ESCCtrl.isReadOnly = isReadOnly;

			}
			else if(this.AppID==0&&this.Application==null)
			{
				//SET PROPERTIES OF FORM CONTROL AND LOAD CTRL
				ESCCtrl.isCoveredPerson = !this.Transition;
				ESCCtrl.isReadOnly = isReadOnly;

			}
			else
			{
				WebUtility.Go2ErrorPage( this.Page, "wrong Application ID" );
			}
		}
		#endregion

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
		}
		#endregion

		#region BuildObjects

		private DataTable BuildSessionTable(string SessionName)
		{
			DataTable dataTable = null;
			object SessDataTable = Session[SessionName];
			if(SessDataTable!=null)
			{
				dataTable = (DataTable)SessDataTable;
			}
			return dataTable;
		}
		#endregion

		
		private Employee GetUser(string name)
		{
			IUser userService = AppContainer.Instance[ServiceConst.UserService] as IUser;
			return userService.GetUser(name);
		}

		private void BindAppDepartment(ref BEGDC.CC.Entity.Application app)
		{
			IUtility utility = AppContainer.Instance[ServiceConst.UtilityService] as IUtility;
			app.IsTransition = this.Transition;
			//			if(app.SomeoneElseNo!=null)
			//			{
			//				app.DepartmentType = utility.GetDicItem(app.SomeoneElseNo.Department.DepartmentType.DicItemKey,  BEGDC.CC.BL.Common.DicType.DepartmentType);
			//				
			//				app.DepartmentName = new Department();
			//				app.DepartmentName.Id = Convert.ToInt32(app.SomeoneElseNo.Department.Id);
			//			}
			//			else
			//			{
			//				if(app.DepartmentType==null&&this.Department!="")
			//				{
			//					app.DepartmentType = utility.GetDicItem(this.Department,  BEGDC.CC.BL.Common.DicType.DepartmentType);
			//				}
			//				if(app.DepartmentName==null&&this.Branch!=null&&this.Branch!="")
			//				{
			//					app.DepartmentName = new Department();
			//					app.DepartmentName.Id = Convert.ToInt32(this.Branch);
			//				}
			//			}
		}

		private bool CheckFormValidation(Entity.Application App)
		{
			IUtility utility = AppContainer.Instance[ServiceConst.UtilityService] as IUtility;
			IESC ESCService = AppContainer.Instance[ServiceConst.ESCService] as IESC;

			if(this.ESCCtrl.CustomerNum==0)
			{
				Page.RegisterClientScriptBlock("","<script>alert('At least one customer should be specified.');</script>");
				return false;
			}
			if(this.ESCCtrl.AccompanyNum==0)
			{
				Page.RegisterClientScriptBlock("","<script>alert('At least one Alcatel-Lucent attendee should be specified.');</script>");
				return false;
			}
			if(this.ESCCtrl.CostCenterNum==0)
			{
				Page.RegisterClientScriptBlock("","<script>alert('At least one cost center code should be specified.');</script>");
				return false;
			}
			if(this.ESCCtrl.IsCustomerNotInCIS)
			{
				Page.RegisterClientScriptBlock("","<script>alert('There are customer(s) not in CIS.');</script>");
				return false;
			}

			//			Employee emp = this.GetUser(HttpContext.Current.User.Identity.Name);
			//			if(this.ESCCtrl.IsSomeoneElse&&this.ESCCtrl.SomeoneEmployee!=null)
			//			{
			//				emp = this.ESCCtrl.SomeoneEmployee;
			//			}

			string Empl = null;
			if(App.IsSSME)
			{
				Empl = ESCService.GetCostCenterHead(BEGDC.CC.BL.Workflow.UserRole.CostCenterHead, App.CostCenterCode.DicItemKey);
				if(Empl=="" || Empl =="0")
				{
					Page.RegisterClientScriptBlock("","<script>alert('No Cost Center Head available.');</script>");
					return false;
				}
			}
			else
			{
				Empl = ESCService.GetOCORoleMemberList(BEGDC.CC.BL.Workflow.UserRole.DeptHead, App.DepartmentType.DicItemKey);
				if(Empl=="" || Empl =="0")
				{
					Page.RegisterClientScriptBlock("","<script>alert('No Department Head available.');</script>");
					return false;
				}

				DataTable table = utility.GetDepartmentFNCByCode(App.DepartmentType.DicItemKey);
				if(table==null||table.Rows.Count==0)
				{
					Page.RegisterClientScriptBlock("","<script>alert('No FNC available.');</script>");
					return false;
				}
			}
			
			return true;
		}

		#region Copy
		private void Btn_Copy_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			try
			{
				IESC ESCService = AppContainer.Instance[ServiceConst.ESCService] as IESC;
				ESCService.CopyCR(this.AppID);
			}
			catch(Exception exp)
			{
				Page.RegisterClientScriptBlock("","<script>alert('" + BEGDC.CC.Resource.SystemMessage.CR002 + "');window.close();</script>");
			}
			Page.RegisterClientScriptBlock("","<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CM004 + "');</script>");

			this.ctrlExport.Visible=true;
		}

		private DataTable InitializeDataTable(System.Data.DataTable dataTable)	
		{
			DataRow dataRow;
			for(int i=0;i<dataTable.Rows.Count;i++)
			{
				dataRow = dataTable.Rows[i];
				dataRow[0] = 0;
			}
			return dataTable;
		}
		#endregion

		#region ButtonStatusSetting
		protected override void ButtonStatusSetting()
		{			
			if( this.Access == null )
				return;

			if((this.Access.IsReadOnly || this.IsView))
				isReadOnly = true;
		}
		#endregion

		#region Reply
		private void Btn_Reply_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			try
			{
				IESC ESCService = AppContainer.Instance[ServiceConst.ESCService] as IESC;
				IUtility utility = AppContainer.Instance[ServiceConst.UtilityService] as IUtility;
				BEGDC.CC.Entity.Application App = ESCService.GetApplication(this.AppID);

				Application app = new Application();
				app.IsTransition = this.Transition;
				if(this.Application!=null)
				{
					app.Id = this.AppID;
					app.AppNo = this.Application.AppNo;
					app.IsTransition = this.Application.IsTransition;
					app.NeedEVPApproval = this.Application.NeedEVPApproval;
					app.DepartmentType = this.Application.DepartmentType;
					app.DepartmentName = this.Application.DepartmentName;
				}

				CustomerInfo customer = new CustomerInfo();
				BusinessPurpose business = new BusinessPurpose();
				Topic topic = new Topic();
				SalesTeamInfo salesTeam = new SalesTeamInfo();
				LogisticalInfo logist = new LogisticalInfo();
				PaymentInfo payment = new PaymentInfo();
				IList customerAttendee = new ArrayList();
				IList alAttendee = new ArrayList();
				IList site = new ArrayList();
				IList cost = new ArrayList();
				IList contract = new ArrayList();
				//update Jovi
				DataTable HotelTable = null;
				DataTable CompanyCarTable = null;
				DataTable LeaseCarTable = null;

				ESCCtrl.BuildApplication(ref app, ref customer, ref business, ref topic, ref salesTeam, ref logist, ref payment, ref customerAttendee, ref alAttendee, ref site, ref cost, ref contract, ref HotelTable, ref CompanyCarTable, ref LeaseCarTable);
				//app.ApplicationType = WorkflowTypes.ESC;
				ESCService.SaveEZApplication(app, customer, business, topic, salesTeam, logist, payment, customerAttendee, alAttendee, site, cost, contract, HotelTable, CompanyCarTable, LeaseCarTable, false, true);

				ESCService.ReplyQuery(Convert.ToInt64(Request.QueryString["FlowID"]), WebUtility.DeCodeString(Server, tbComment.Text));

				Page.RegisterClientScriptBlock("","<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CR001 + "');window.close();</script>");
			}
			catch(Exception exp)
			{
				Page.RegisterClientScriptBlock("","<script>alert('" + BEGDC.CC.Resource.SystemMessage.CR002 + "');window.close();</script>");
			}
		}
		#endregion
	}
}
